#include <iostream>
#include <string>
#include <mysql/mysql.h>

const std::string host = "localhost";
const std::string user = "connector";
const std::string passwd = "123456";
const std::string db = "conn";
const unsigned int port = 3306;

int main()
{
    // std::cout << "mysql client version: " << mysql_get_client_info() << std::endl;

    MYSQL* my = mysql_init(nullptr); // 创建一个句柄
    if (nullptr == my)
    {
        std::cerr << "init MySQL error" << std::endl;
        return 1;
    }    

    // 连接到MySQL服务器
    if (mysql_real_connect(my, host.c_str(), user.c_str(), passwd.c_str(), db.c_str(), port, nullptr, 0) == nullptr)
    {
        std::cerr << "connect MySQL error" << std::endl;
        return 2;
    }
    mysql_set_character_set(my, "utf8"); // 设置字符编码支持中文

    std::string sql = "select * from user";
    int n = mysql_query(my, sql.c_str());
    if (n == 0)
    {
        std::cout << sql << " success" << std::endl;
    }
    else
    {
        std::cerr << sql << " failed" << std::endl; 
        return 3;
    }
    MYSQL_RES* res = mysql_store_result(my);
    if (nullptr == res)
    {
        std::cerr << "mysql_store_result error" << std::endl;
        return 4;
    }
    // 获取行数和列数
    int rows = mysql_num_rows(res);
    int fields = mysql_num_fields(res);
    std::cout << "行: " << rows << std::endl;
    std::cout << "列: " << fields << std::endl;
    
    // 获取表的属性
    MYSQL_FIELD* fields_array = mysql_fetch_fields(res);
    for (int i = 0; i < fields; i++)
    {
        std::cout << fields_array[i].name << "\t";
    }
    std::cout << "\n";
    
    for (int i = 0; i < rows; i++)
    {
        // MYSQL_ROW = char**
        MYSQL_ROW row = mysql_fetch_row(res);
        for (int j = 0; j < fields; j++)
        {
            std::cout << row[j] << "\t";
        }
        std::cout << "\n";
    }
    


    // std::string sql;
    // while (true)
    // {
    //     std::cout << "MySQL>>> ";
    //     if (!std::getline(std::cin, sql) || sql == "quit")
    //     {
    //         std::cout << "bye bye" << std::endl;
    //         break;
    //     }

    //     int n = mysql_query(my, sql.c_str());
    //     if (n == 0)
    //         std::cout << sql << " success " << n << std::endl;
    //     else
    //         std::cerr << sql << " failed: " << n << std::endl; 
    // }

    std::cout << "connect success" << std:: endl;

    mysql_free_result(res); // 释放结果集
    mysql_close(my);

    return 0;
}